package com.liangxw.site.user.service;

import com.liangxw.site.user.bean.User;
import com.liangxw.site.user.dao.UserMapper;
import com.lxw.site.common.DataResult;
import com.lxw.site.utils.AccountValidatorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.regex.Pattern;

/**
 * @author 梁星武
 * @version 0.0.3
 * @description UserService
 * @since 2021/3/17 22:05
 */
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper ;

    public DataResult findUserList(String id){
        DataResult result = new DataResult();
        List<User> userList = userMapper.findUserList(id);
        if (userList==null || userList.size() == 0){
            result.setMsg("未查询到该用户");
        }else{
            result.setSuccess(true);
            result.setResult(userList);
        }

        return  result ;
    }

    /**
     * 用户登录：手机/邮箱/用户名 登录
     * @param username
     * @param password
     * @return
     */
    public DataResult userLogin(String username,String password){
        DataResult result = new DataResult();
        User user = null ;
        //用正则表达式匹配 是否为邮箱 和 手机号.其他默认为username
        if (AccountValidatorUtil.isEmail(username)){
            user = userMapper.findUserByEmail(username);
        }else if (AccountValidatorUtil.isMobile(username)){
            user = userMapper.findUserByTelephone(username);
        }else{//默认是 用户名登录
            user= userMapper.findUserByUsername(username);
        }
        if (user == null){
            //登录失败:用户名不存在
            result.setSuccess(false);
            result.setMsg("该登录名不存在");
        }else{//对比 密码 Bcrypt加密
            boolean checkpw = BCrypt.checkpw(password, user.getPassword());
            if (checkpw){
                //成功
                result.setSuccess(true);
                result.setMsg("登录成功");
                result.setData(user);
            }else {
                result.setMsg("密码错误");
            }
        }
        //用户名为 1-6的长度的字符串
        return  result ;
    }

    public static void main(String[] args) {
        System.out.println(BCrypt.hashpw("123456", BCrypt.gensalt()));
    }
}
